import { cwd } from "process";
import { join, normalize } from "path";
import { Options } from "../../types/options";
import { normalizePath, resolveTempFile } from "../../utils/common";
import { CONFIG } from "../../utils/config";

export async function uploadZipFolder(
    options: Pick<Options, "uploadList" | "sshList">
) {
    const { sshList, uploadList } = options;

    await Promise.all(
        uploadList.map(async (upload) => {
            const { host, fileList } = upload;
            const ssh = sshList.find((item) => item.host === host);
            if (!ssh) {
                /* 未找到host为xxx的ssh配置信息 */
                throw new Error(
                    `The ssh configuration with host ${host} is not found`
                );
            }
            const nodeSSH = await ssh.ssh.connect(ssh);

            await Promise.all(
                fileList.map(async (file) => {
                    const { id, remotePath } = file;

                    const zipFileFullName = `${id}${CONFIG.ZIP_SUFFIX}`;

                    const localZipFilePath = resolveTempFile(zipFileFullName);
                    const remoteZipFilePath = normalizePath(
                        join(remotePath, zipFileFullName).replace(/\\/g, "/")
                    );

                    await nodeSSH.putFile(localZipFilePath, remoteZipFilePath);

                    // unzip file
                    const res = await nodeSSH.execCommand(
                        // `unzip -o ${remoteZipFilePath} -d ${remotePath}`
                        `tar -xvf ${remoteZipFilePath} -C ${normalizePath(
                            remotePath
                        )}`
                    );
                    if (res.code) {
                        console.log(res);

                        throw new Error(`unzip error: ${res.stderr}`);
                    }
                    /* 删除zip */
                    let res2 = await nodeSSH.execCommand(
                        `rm ${remoteZipFilePath}`
                    );
                    if (res2.code) {
                        res2 = await nodeSSH.execCommand(
                            `del ${normalize(remoteZipFilePath)}`
                        );
                        if (res2.code) {
                            throw new Error(
                                `rm zip file error: ${res2.stderr}`
                            );
                        }
                    }
                })
            );
        })
    );
}
